package com.atguigu.gulimall.service.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String userinfo = (String) redisTemplate.opsForValue().get(token);
        return userinfo;
    }

    @GetMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response){

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功跳转,跳回到原来到地方
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid,username);
            //还要给浏览器留一个登录的记号,给ssoserver的域名添加一个coookie
            Cookie cookie = new Cookie("sso_token",uuid);
            response.addCookie(cookie);
            return "redirect:"+url+"?token="+uuid;
        }
        //登录失败跳转,到登录页
        return "login";
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        //如果cookie不为空，说明有人登录过
        if (!StringUtils.isEmpty(sso_token)){
            return "redirect:"+url+"?token="+sso_token;
        }
        //redirect_url 登录成功后返回到页面
        model.addAttribute("url",url);

        //登录成功跳转,跳回到原来到地方
        return "login";
    }
}
